package servlet;

import dao.EquipmentDao;
import dao.EquipmentDaoImpl;
import dao.TableUsingDaoImpl;
import dao.UsingDaoImpl;
import utils.string.session.SessionStringUtil;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

public class DeleteUsingServlet extends HttpServlet {
    //删除Using表中的使用
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        handleData(req,resp);
    }
    //不知道为什么，明明method选择的是post，但是执行的是get，干脆都是执行相同的功能
    private void handleData(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int usingId = Integer.parseInt(req.getParameter("using_Id"));
        int equip_id = Integer.parseInt(req.getParameter("equip_id"));
        int equip_num = Integer.parseInt(req.getParameter("equip_num"));
        UsingDaoImpl usingDao = new UsingDaoImpl();
        //在设备表中的数据也得需修改
        EquipmentDaoImpl equipmentDao = new EquipmentDaoImpl();
        equipmentDao.changeEquipment(equip_id,equip_num, EquipmentDao.ADD_EQUIPMENT_NUM);
        Boolean flag = usingDao.deleteByID(usingId);
        if(flag){
            jumpToJsp(req,resp);
        }
    }

    private void jumpToJsp(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //负责数据传递
        User user = (User) req.getSession().getAttribute(SessionStringUtil.USER);
        TableUsingDaoImpl tableUsingDao = new TableUsingDaoImpl();
        HashMap usings = tableUsingDao.selectAll();
        req.getSession().setAttribute(SessionStringUtil.ALL_USING,usings);
        if(user.getAuth_id() == 1){
            resp.sendRedirect("/equipmentManager_war_explode/manageAllUsing.jsp");//跳转到管理者的Using界面
        }else{
            resp.sendRedirect("/equipmentManager_war_explode/manageUserUsing.jsp");//普通用户的界面
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleData(req,resp);
    }
}
